import React, { Component, Fragment } from 'react';
import axios from 'axios'
import { withRouter } from 'react-router-dom'

/* @desc:不拦截response的请求名 */
const unInterceptorUrl = []

class HttpIntercepter extends Component {

    /* @desc:检测请求名是否需要拦截 */
    checkUrl = (url, unInterArr) => {
        let arr = url.split('/'), flag = true
        unInterArr.forEach(item => {
            if (item === arr[arr.length - 1]) {
                flag = false
            }
        })
        return flag
    }

    request = config => {
        return config
    }

    response = response => {
        if (response.data.code !== 0 && this.checkUrl(response.config.url, unInterceptorUrl)) {
            alert(response.data.msg)
        }
        return response.data;
    }

    setIntercepter = () => {
        let vm = this
        axios.interceptors.request.use(vm.request)
        axios.interceptors.response.use(vm.response)
    }

    componentDidMount() {
        this.setIntercepter()
    }

    render() {
        const { children } = this.props
        return <Fragment>{children}</Fragment>
    }
}

export default withRouter(HttpIntercepter)